package com.yunke.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunke.dto.YunkeDistributorApplyDto;
import com.yunke.dto.YunkeDistributorWithdrawDto;
import com.yunke.entity.*;
import com.yunke.mapper.*;
import com.yunke.service.YunkeDistributorService;
import com.yunke.service.YunkeUserService;
import com.yunke.vo.YunkeDistributorCommissionVo;
import com.yunke.vo.YunkeDistributorVo;
import com.yunke.vo.YunkeDistributorWithdrawVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static com.yunke.common.util.YunkeInviteCodeUtil.generateInviteCode;

/**
 * 分销体系服务实现类
 *
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class YunkeDistributorServiceImpl implements YunkeDistributorService {

    private final YunkeDistributorMapper distributorMapper;
    private final YunkeDistributorCommissionMapper commissionMapper;
    private final YunkeDistributorWithdrawMapper withdrawMapper;
    private final YunkeDistributorConfigMapper configMapper;
    private final YunkeUserService userService;

    @Override
    @Transactional
    public boolean applyDistributor(Long userId, YunkeDistributorApplyDto applyDto) {
        try {
            // 检查用户是否已经是分销商
            YunkeDistributor existing = distributorMapper.selectByUserId(userId);
            if (existing != null) {
                throw new RuntimeException("您已经是分销商，无需重复申请");
            }

            // 检查是否满足申请条件
            if (!checkCanApply(userId)) {
                throw new RuntimeException("您暂时不满足申请条件");
            }

            // 获取用户信息
            YunkeUser user = userService.getById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 创建分销商
            YunkeDistributor distributor = new YunkeDistributor();
            distributor.setUserId(userId);
            distributor.setNickname(applyDto.getNickname());
            distributor.setAvatar(user.getAvatar());
            distributor.setMobile(applyDto.getMobile());
            distributor.setWechat(applyDto.getWechat());
            distributor.setAccountType(applyDto.getAccountType());
            distributor.setAccountInfo(applyDto.getAccountInfo());
            distributor.setAccountName(applyDto.getAccountName());
            distributor.setExtInfo(applyDto.getExtInfo());

            // 生成邀请码
            distributor.setInviteCode(generateInviteCode());

            // 处理上级分销商
            if (StrUtil.isNotBlank(applyDto.getInviteCode())) {
                YunkeDistributor parent = distributorMapper.selectByInviteCode(applyDto.getInviteCode());
                if (parent != null && parent.getAuditStatus() == 1) {
                    distributor.setParentId(parent.getId());
                    distributor.setLevel(parent.getLevel() + 1);
                }
            }

            if (distributor.getLevel() == null) {
                distributor.setLevel(1);
            }

            // 初始化统计数据
            distributor.setTotalCommission(BigDecimal.ZERO);
            distributor.setWithdrawnAmount(BigDecimal.ZERO);
            distributor.setAvailableAmount(BigDecimal.ZERO);
            distributor.setTotalInviteUsers(0);
            distributor.setTotalInviteOrders(0);
            distributor.setMonthCommission(BigDecimal.ZERO);
            distributor.setMonthInviteCount(0);

            // 设置审核状态
            boolean requireAudit = Boolean.parseBoolean(getDistributorConfig("require_audit"));
            distributor.setAuditStatus(requireAudit ? 0 : 1);
            distributor.setDistributorStatus(0);
            distributor.setApplyTime(System.currentTimeMillis());
            
            if (!requireAudit) {
                distributor.setActiveTime(System.currentTimeMillis());
                distributor.setAuditTime(System.currentTimeMillis());
            }

            distributor.setStatus(0);
            distributor.setCreateTime(System.currentTimeMillis());
            distributor.setUpdateTime(System.currentTimeMillis());

            distributorMapper.insert(distributor);

            // 生成推广链接和二维码
            distributor.setPromoteUrl(generatePromoteUrl(distributor.getId()));
            distributor.setPromoteQrcode(generatePromoteQrcode(distributor.getId()));
            distributorMapper.updateById(distributor);

            log.info("用户申请分销商成功，userId: {}, distributorId: {}", userId, distributor.getId());
            return true;
        } catch (Exception e) {
            log.error("申请分销商失败，userId: {}", userId, e);
            throw new RuntimeException("申请失败：" + e.getMessage());
        }
    }

    @Override
    public YunkeDistributorVo getDistributorInfo(Long userId) {
        try {
            YunkeDistributor distributor = distributorMapper.selectByUserId(userId);
            if (distributor == null) {
                return null;
            }

            YunkeDistributorVo vo = BeanUtil.copyProperties(distributor, YunkeDistributorVo.class);
            
            // 获取上级分销商昵称
            if (distributor.getParentId() != null) {
                YunkeDistributor parent = distributorMapper.selectById(distributor.getParentId());
                if (parent != null) {
                    vo.setParentNickname(parent.getNickname());
                }
            }

            // 设置状态名称
            vo.setAuditStatusName(getAuditStatusName(distributor.getAuditStatus()));
            vo.setDistributorStatusName(getDistributorStatusName(distributor.getDistributorStatus()));
            vo.setAccountTypeName(getAccountTypeName(distributor.getAccountType()));

            // 获取团队统计
            YunkeDistributorVo.YunkeDistributorTeamStatsVo teamStats = new YunkeDistributorVo.YunkeDistributorTeamStatsVo();
            teamStats.setDirectCount(distributorMapper.countDirectMembers(distributor.getId()));
            teamStats.setTotalTeamCount(distributorMapper.countTeamMembers(distributor.getId()));
            teamStats.setLevel1Count(distributorMapper.selectChildDistributors(distributor.getId(), 1).size());
            teamStats.setLevel2Count(distributorMapper.selectChildDistributors(distributor.getId(), 2).size());
            teamStats.setLevel3Count(distributorMapper.selectChildDistributors(distributor.getId(), 3).size());
            vo.setTeamStats(teamStats);

            // 获取佣金统计
            YunkeDistributorVo.YunkeDistributorCommissionStatsVo commissionStats = new YunkeDistributorVo.YunkeDistributorCommissionStatsVo();
            commissionStats.setTodayCommission(commissionMapper.selectTodayCommission(distributor.getId()));
            commissionStats.setYesterdayCommission(commissionMapper.selectYesterdayCommission(distributor.getId()));
            commissionStats.setWeekCommission(commissionMapper.selectWeekCommission(distributor.getId()));
            commissionStats.setMonthCommission(commissionMapper.selectMonthCommission(distributor.getId()));
            commissionStats.setTotalCommission(distributor.getTotalCommission());
            vo.setCommissionStats(commissionStats);

            return vo;
        } catch (Exception e) {
            log.error("获取分销商信息失败，userId: {}", userId, e);
            return null;
        }
    }

    @Override
    public IPage<YunkeDistributorVo> getDistributorPage(Integer current, Integer size, String nickname, 
                                                        String mobile, Integer level, Integer auditStatus, 
                                                        Integer distributorStatus) {
        try {
            Page<YunkeDistributor> page = new Page<>(current, size);
            IPage<YunkeDistributor> distributorPage = distributorMapper.selectDistributorPage(
                    page, nickname, mobile, level, auditStatus, distributorStatus);

            return distributorPage.convert(distributor -> {
                YunkeDistributorVo vo = BeanUtil.copyProperties(distributor, YunkeDistributorVo.class);
                vo.setAuditStatusName(getAuditStatusName(distributor.getAuditStatus()));
                vo.setDistributorStatusName(getDistributorStatusName(distributor.getDistributorStatus()));
                vo.setAccountTypeName(getAccountTypeName(distributor.getAccountType()));

                // 获取上级分销商昵称
                if (distributor.getParentId() != null) {
                    YunkeDistributor parent = distributorMapper.selectById(distributor.getParentId());
                    if (parent != null) {
                        vo.setParentNickname(parent.getNickname());
                    }
                }

                return vo;
            });
        } catch (Exception e) {
            log.error("查询分销商列表失败", e);
            return new Page<>();
        }
    }

    @Override
    @Transactional
    public boolean auditDistributor(Long distributorId, Integer auditStatus, String auditRemark, Long auditorId) {
        try {
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor == null) {
                throw new RuntimeException("分销商不存在");
            }

            distributor.setAuditStatus(auditStatus);
            distributor.setAuditRemark(auditRemark);
            distributor.setAuditTime(System.currentTimeMillis());
            distributor.setAuditorId(auditorId);

            if (auditStatus == 1) { // 审核通过
                distributor.setActiveTime(System.currentTimeMillis());
                distributor.setDistributorStatus(0); // 设为正常状态
            }

            distributor.setUpdateTime(System.currentTimeMillis());
            distributorMapper.updateById(distributor);

            log.info("审核分销商成功，distributorId: {}, auditStatus: {}", distributorId, auditStatus);
            return true;
        } catch (Exception e) {
            log.error("审核分销商失败，distributorId: {}", distributorId, e);
            throw new RuntimeException("审核失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean updateDistributorStatus(Long distributorId, Integer distributorStatus) {
        try {
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor == null) {
                throw new RuntimeException("分销商不存在");
            }

            distributor.setDistributorStatus(distributorStatus);
            distributor.setUpdateTime(System.currentTimeMillis());
            distributorMapper.updateById(distributor);

            log.info("更新分销商状态成功，distributorId: {}, status: {}", distributorId, distributorStatus);
            return true;
        } catch (Exception e) {
            log.error("更新分销商状态失败，distributorId: {}", distributorId, e);
            throw new RuntimeException("更新状态失败：" + e.getMessage());
        }
    }

    @Override
    public List<YunkeDistributorVo> getTeamList(Long distributorId, Integer level) {
        try {
            List<YunkeDistributor> distributors = distributorMapper.selectChildDistributors(distributorId, level);
            return distributors.stream().map(distributor -> {
                YunkeDistributorVo vo = BeanUtil.copyProperties(distributor, YunkeDistributorVo.class);
                vo.setAuditStatusName(getAuditStatusName(distributor.getAuditStatus()));
                vo.setDistributorStatusName(getDistributorStatusName(distributor.getDistributorStatus()));
                vo.setAccountTypeName(getAccountTypeName(distributor.getAccountType()));
                return vo;
            }).toList();
        } catch (Exception e) {
            log.error("获取团队列表失败，distributorId: {}", distributorId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public String generatePromoteUrl(Long distributorId) {
        try {
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor == null) {
                return null;
            }

            String baseUrl = getDistributorConfig("promote_base_url");
            if (StrUtil.isBlank(baseUrl)) {
                baseUrl = "https://app.yunke.com";
            }

            return baseUrl + "/register?invite=" + distributor.getInviteCode();
        } catch (Exception e) {
            log.error("生成推广链接失败，distributorId: {}", distributorId, e);
            return null;
        }
    }

    @Override
    public String generatePromoteQrcode(Long distributorId) {
        try {
            String promoteUrl = generatePromoteUrl(distributorId);
            if (StrUtil.isBlank(promoteUrl)) {
                return null;
            }

            // 这里应该调用二维码生成服务
            // 暂时返回一个示例链接
            return "/qrcode/distributor_" + distributorId + ".png";
        } catch (Exception e) {
            log.error("生成推广二维码失败，distributorId: {}", distributorId, e);
            return null;
        }
    }

    @Override
    @Transactional
    public boolean recordCommission(Long distributorUserId, Long orderId, String orderNo, 
                                  Long customerUserId, Integer commissionType, BigDecimal orderAmount) {
        try {
            // 查找分销商
            YunkeDistributor distributor = distributorMapper.selectByUserId(distributorUserId);
            if (distributor == null || distributor.getAuditStatus() != 1 || distributor.getDistributorStatus() != 0) {
                return false; // 分销商不存在或状态异常
            }

            // 获取佣金配置
            BigDecimal commissionRate = getCommissionRate(distributor.getLevel(), commissionType);
            if (commissionRate == null || commissionRate.compareTo(BigDecimal.ZERO) <= 0) {
                return false; // 没有佣金比例
            }

            // 计算佣金
            BigDecimal commissionAmount = orderAmount.multiply(commissionRate).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);

            // 获取客户昵称
            YunkeUser customer = userService.getById(customerUserId);
            String customerNickname = customer != null ? customer.getNickname() : "未知用户";

            // 创建佣金记录
            YunkeDistributorCommission commission = new YunkeDistributorCommission();
            commission.setDistributorId(distributor.getId());
            commission.setDistributorUserId(distributorUserId);
            commission.setOrderId(orderId);
            commission.setOrderNo(orderNo);
            commission.setCustomerUserId(customerUserId);
            commission.setCustomerNickname(customerNickname);
            commission.setCommissionType(commissionType);
            commission.setCommissionLevel(distributor.getLevel());
            commission.setOrderAmount(orderAmount);
            commission.setCommissionRate(commissionRate);
            commission.setCommissionAmount(commissionAmount);
            commission.setActualAmount(commissionAmount); // 暂时不扣除税费
            commission.setCommissionStatus(0); // 待结算
            commission.setStatus(0);
            commission.setCreateTime(System.currentTimeMillis());
            commission.setUpdateTime(System.currentTimeMillis());

            commissionMapper.insert(commission);

            // 更新分销商统计
            distributorMapper.updateCommissionStats(distributor.getId(), commissionAmount, 1);
            distributorMapper.updatePromoteStats(distributor.getId(), 0, 1);

            log.info("记录分销佣金成功，distributorUserId: {}, commissionAmount: {}", distributorUserId, commissionAmount);
            return true;
        } catch (Exception e) {
            log.error("记录分销佣金失败，distributorUserId: {}", distributorUserId, e);
            return false;
        }
    }

    @Override
    public IPage<YunkeDistributorCommissionVo> getCommissionPage(Long distributorId, Integer current, Integer size,
                                                                 Integer commissionType, Integer commissionStatus,
                                                                 Long startTime, Long endTime) {
        try {
            Page<YunkeDistributorCommission> page = new Page<>(current, size);
            IPage<YunkeDistributorCommission> commissionPage = commissionMapper.selectCommissionPage(
                    page, distributorId, commissionType, commissionStatus, startTime, endTime);

            return commissionPage.convert(commission -> {
                YunkeDistributorCommissionVo vo = BeanUtil.copyProperties(commission, YunkeDistributorCommissionVo.class);
                vo.setCommissionTypeName(getCommissionTypeName(commission.getCommissionType()));
                vo.setCommissionLevelName(getCommissionLevelName(commission.getCommissionLevel()));
                vo.setCommissionStatusName(getCommissionStatusName(commission.getCommissionStatus()));

                // 获取分销商昵称
                YunkeDistributor distributor = distributorMapper.selectById(commission.getDistributorId());
                if (distributor != null) {
                    vo.setDistributorNickname(distributor.getNickname());
                }

                return vo;
            });
        } catch (Exception e) {
            log.error("查询佣金记录失败，distributorId: {}", distributorId, e);
            return new Page<>();
        }
    }

    @Override
    public Map<String, Object> getCommissionStats(Long distributorId, Long startTime, Long endTime) {
        try {
            Map<String, Object> stats = commissionMapper.selectCommissionSummary(distributorId, startTime, endTime);
            if (stats == null) {
                stats = new HashMap<>();
            }

            // 获取各类型佣金统计
            List<Map<String, Object>> typeStats = commissionMapper.selectCommissionByType(distributorId, startTime, endTime);
            stats.put("typeStats", typeStats);

            // 获取各等级佣金统计
            List<Map<String, Object>> levelStats = commissionMapper.selectCommissionByLevel(distributorId, startTime, endTime);
            stats.put("levelStats", levelStats);

            // 获取趋势图数据
            List<Map<String, Object>> trendData = commissionMapper.selectCommissionTrend(distributorId, 30);
            stats.put("trendData", trendData);

            return stats;
        } catch (Exception e) {
            log.error("获取佣金统计失败，distributorId: {}", distributorId, e);
            return new HashMap<>();
        }
    }

    @Override
    @Transactional
    public boolean applyWithdraw(Long distributorId, YunkeDistributorWithdrawDto withdrawDto) {
        try {
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor == null) {
                throw new RuntimeException("分销商不存在");
            }

            // 检查可提现金额
            if (distributor.getAvailableAmount().compareTo(withdrawDto.getApplyAmount()) < 0) {
                throw new RuntimeException("可提现金额不足");
            }

            // 检查最小提现金额
            BigDecimal minWithdrawAmount = new BigDecimal(getDistributorConfig("min_withdraw_amount"));
            if (withdrawDto.getApplyAmount().compareTo(minWithdrawAmount) < 0) {
                throw new RuntimeException("提现金额不能小于" + minWithdrawAmount + "元");
            }

            // 计算手续费
            BigDecimal feeRate = new BigDecimal(getDistributorConfig("withdraw_fee_rate"));
            BigDecimal feeAmount = withdrawDto.getApplyAmount().multiply(feeRate).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
            
            BigDecimal feeMin = new BigDecimal(getDistributorConfig("withdraw_fee_min"));
            BigDecimal feeMax = new BigDecimal(getDistributorConfig("withdraw_fee_max"));
            
            if (feeAmount.compareTo(feeMin) < 0) {
                feeAmount = feeMin;
            }
            if (feeAmount.compareTo(feeMax) > 0) {
                feeAmount = feeMax;
            }

            BigDecimal actualAmount = withdrawDto.getApplyAmount().subtract(feeAmount);

            // 生成提现单号
            String withdrawNo = "WD" + System.currentTimeMillis() + IdUtil.randomUUID().substring(0, 6);

            // 创建提现记录
            YunkeDistributorWithdraw withdraw = new YunkeDistributorWithdraw();
            withdraw.setDistributorId(distributorId);
            withdraw.setDistributorUserId(distributor.getUserId());
            withdraw.setWithdrawNo(withdrawNo);
            withdraw.setApplyAmount(withdrawDto.getApplyAmount());
            withdraw.setFeeAmount(feeAmount);
            withdraw.setActualAmount(actualAmount);
            withdraw.setAccountType(withdrawDto.getAccountType());
            withdraw.setAccountInfo(withdrawDto.getAccountInfo());
            withdraw.setAccountName(withdrawDto.getAccountName());
            withdraw.setWithdrawStatus(0); // 待审核
            withdraw.setApplyTime(System.currentTimeMillis());
            withdraw.setRemark(withdrawDto.getRemark());
            withdraw.setStatus(0);
            withdraw.setCreateTime(System.currentTimeMillis());
            withdraw.setUpdateTime(System.currentTimeMillis());

            withdrawMapper.insert(withdraw);

            // 冻结可提现金额
            distributor.setAvailableAmount(distributor.getAvailableAmount().subtract(withdrawDto.getApplyAmount()));
            distributor.setUpdateTime(System.currentTimeMillis());
            distributorMapper.updateById(distributor);

            log.info("申请提现成功，distributorId: {}, amount: {}", distributorId, withdrawDto.getApplyAmount());
            return true;
        } catch (Exception e) {
            log.error("申请提现失败，distributorId: {}", distributorId, e);
            throw new RuntimeException("申请失败：" + e.getMessage());
        }
    }

    @Override
    public IPage<YunkeDistributorWithdrawVo> getWithdrawPage(Long distributorId, Integer current, Integer size,
                                                             Integer withdrawStatus, Long startTime, Long endTime) {
        try {
            Page<YunkeDistributorWithdraw> page = new Page<>(current, size);
            IPage<YunkeDistributorWithdraw> withdrawPage = withdrawMapper.selectWithdrawPage(
                    page, distributorId, withdrawStatus, startTime, endTime);

            return withdrawPage.convert(withdraw -> {
                YunkeDistributorWithdrawVo vo = BeanUtil.copyProperties(withdraw, YunkeDistributorWithdrawVo.class);
                vo.setAccountTypeName(getAccountTypeName(withdraw.getAccountType()));
                vo.setWithdrawStatusName(getWithdrawStatusName(withdraw.getWithdrawStatus()));

                // 获取分销商昵称
                YunkeDistributor distributor = distributorMapper.selectById(withdraw.getDistributorId());
                if (distributor != null) {
                    vo.setDistributorNickname(distributor.getNickname());
                }

                // 获取审核人和处理人昵称
                if (withdraw.getAuditorId() != null) {
                    YunkeUser auditor = userService.getById(withdraw.getAuditorId());
                    if (auditor != null) {
                        vo.setAuditorNickname(auditor.getNickname());
                    }
                }

                if (withdraw.getProcessorId() != null) {
                    YunkeUser processor = userService.getById(withdraw.getProcessorId());
                    if (processor != null) {
                        vo.setProcessorNickname(processor.getNickname());
                    }
                }

                return vo;
            });
        } catch (Exception e) {
            log.error("查询提现记录失败，distributorId: {}", distributorId, e);
            return new Page<>();
        }
    }

    @Override
    @Transactional
    public boolean auditWithdraw(Long withdrawId, Integer auditStatus, String auditRemark, Long auditorId) {
        try {
            YunkeDistributorWithdraw withdraw = withdrawMapper.selectById(withdrawId);
            if (withdraw == null) {
                throw new RuntimeException("提现记录不存在");
            }

            if (withdraw.getWithdrawStatus() != 0) {
                throw new RuntimeException("该提现申请已处理");
            }

            withdraw.setWithdrawStatus(auditStatus);
            withdraw.setAuditTime(System.currentTimeMillis());
            withdraw.setAuditorId(auditorId);
            withdraw.setAuditRemark(auditRemark);
            withdraw.setUpdateTime(System.currentTimeMillis());
            withdrawMapper.updateById(withdraw);

            // 如果审核拒绝，释放冻结金额
            if (auditStatus == 2) {
                YunkeDistributor distributor = distributorMapper.selectById(withdraw.getDistributorId());
                if (distributor != null) {
                    distributor.setAvailableAmount(distributor.getAvailableAmount().add(withdraw.getApplyAmount()));
                    distributor.setUpdateTime(System.currentTimeMillis());
                    distributorMapper.updateById(distributor);
                }
            }

            log.info("审核提现成功，withdrawId: {}, auditStatus: {}", withdrawId, auditStatus);
            return true;
        } catch (Exception e) {
            log.error("审核提现失败，withdrawId: {}", withdrawId, e);
            throw new RuntimeException("审核失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean processWithdraw(Long withdrawId, Long processorId) {
        try {
            YunkeDistributorWithdraw withdraw = withdrawMapper.selectById(withdrawId);
            if (withdraw == null) {
                throw new RuntimeException("提现记录不存在");
            }

            if (withdraw.getWithdrawStatus() != 1) {
                throw new RuntimeException("该提现申请未通过审核");
            }

            // 更新提现状态
            withdraw.setWithdrawStatus(4); // 已完成
            withdraw.setProcessTime(System.currentTimeMillis());
            withdraw.setProcessorId(processorId);
            withdraw.setCompleteTime(System.currentTimeMillis());
            withdraw.setUpdateTime(System.currentTimeMillis());
            withdrawMapper.updateById(withdraw);

            // 更新分销商已提现金额
            YunkeDistributor distributor = distributorMapper.selectById(withdraw.getDistributorId());
            if (distributor != null) {
                distributor.setWithdrawnAmount(distributor.getWithdrawnAmount().add(withdraw.getApplyAmount()));
                distributor.setUpdateTime(System.currentTimeMillis());
                distributorMapper.updateById(distributor);
            }

            log.info("处理提现成功，withdrawId: {}", withdrawId);
            return true;
        } catch (Exception e) {
            log.error("处理提现失败，withdrawId: {}", withdrawId, e);
            throw new RuntimeException("处理失败：" + e.getMessage());
        }
    }

    @Override
    public String getDistributorConfig(String configKey) {
        try {
            YunkeDistributorConfig config = configMapper.selectByConfigKey(configKey);
            return config != null ? config.getConfigValue() : "";
        } catch (Exception e) {
            log.error("获取分销配置失败，configKey: {}", configKey, e);
            return "";
        }
    }

    @Override
    @Transactional
    public boolean updateDistributorConfig(String configKey, String configValue) {
        try {
            YunkeDistributorConfig config = configMapper.selectByConfigKey(configKey);
            if (config == null) {
                // 创建新配置
                config = new YunkeDistributorConfig();
                config.setConfigKey(configKey);
                config.setConfigValue(configValue);
                config.setEnabled(true);
                config.setStatus(0);
                config.setCreateTime(System.currentTimeMillis());
                config.setUpdateTime(System.currentTimeMillis());
                configMapper.insert(config);
            } else {
                // 更新配置
                config.setConfigValue(configValue);
                config.setUpdateTime(System.currentTimeMillis());
                configMapper.updateById(config);
            }

            log.info("更新分销配置成功，configKey: {}, configValue: {}", configKey, configValue);
            return true;
        } catch (Exception e) {
            log.error("更新分销配置失败，configKey: {}", configKey, e);
            return false;
        }
    }

    @Override
    public boolean checkCanApply(Long userId) {
        try {
            // 检查用户是否存在
            YunkeUser user = userService.getById(userId);
            if (user == null) {
                return false;
            }

            // 检查是否已实名认证
            if (user.getIsRealNameAuth() == null || !user.getIsRealNameAuth()) {
                return false;
            }

            // 检查是否已经是分销商
            YunkeDistributor existing = distributorMapper.selectByUserId(userId);
            if (existing != null) {
                return false;
            }

            return true;
        } catch (Exception e) {
            log.error("检查申请条件失败，userId: {}", userId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean bindParentDistributor(Long userId, String inviteCode) {
        try {
            if (StrUtil.isBlank(inviteCode)) {
                return false;
            }

            YunkeDistributor parent = distributorMapper.selectByInviteCode(inviteCode);
            if (parent == null || parent.getAuditStatus() != 1) {
                return false;
            }

            // 这里可以记录用户与分销商的绑定关系
            // 在用户注册或首次消费时会用到
            
            log.info("绑定上级分销商成功，userId: {}, parentId: {}", userId, parent.getId());
            return true;
        } catch (Exception e) {
            log.error("绑定上级分销商失败，userId: {}", userId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean settleCommissions(Long distributorId, List<Long> commissionIds) {
        try {
            if (commissionIds == null || commissionIds.isEmpty()) {
                return false;
            }

            String settleBatchNo = "ST" + System.currentTimeMillis();
            Long settleTime = System.currentTimeMillis();

            // 批量更新佣金状态
            int updated = commissionMapper.batchUpdateStatus(commissionIds, 1, settleBatchNo, settleTime);

            // 计算结算金额
            LambdaQueryWrapper<YunkeDistributorCommission> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(YunkeDistributorCommission::getId, commissionIds);
            List<YunkeDistributorCommission> commissions = commissionMapper.selectList(wrapper);
            
            BigDecimal totalAmount = commissions.stream()
                    .map(YunkeDistributorCommission::getActualAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 更新分销商可提现金额
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor != null) {
                distributor.setAvailableAmount(distributor.getAvailableAmount().add(totalAmount));
                distributor.setUpdateTime(System.currentTimeMillis());
                distributorMapper.updateById(distributor);
            }

            log.info("结算佣金成功，distributorId: {}, amount: {}, count: {}", distributorId, totalAmount, updated);
            return true;
        } catch (Exception e) {
            log.error("结算佣金失败，distributorId: {}", distributorId, e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getDistributorOverview(Long distributorId) {
        try {
            Map<String, Object> overview = new HashMap<>();
            
            YunkeDistributor distributor = distributorMapper.selectById(distributorId);
            if (distributor == null) {
                return overview;
            }

            // 基础信息
            overview.put("totalCommission", distributor.getTotalCommission());
            overview.put("availableAmount", distributor.getAvailableAmount());
            overview.put("withdrawnAmount", distributor.getWithdrawnAmount());
            overview.put("totalInviteUsers", distributor.getTotalInviteUsers());
            overview.put("totalInviteOrders", distributor.getTotalInviteOrders());

            // 今日数据
            overview.put("todayCommission", commissionMapper.selectTodayCommission(distributorId));
            overview.put("todayWithdraw", withdrawMapper.selectTodayWithdrawAmount(distributorId));

            // 团队数据
            overview.put("directCount", distributorMapper.countDirectMembers(distributorId));
            overview.put("totalTeamCount", distributorMapper.countTeamMembers(distributorId));

            // 趋势数据
            overview.put("commissionTrend", commissionMapper.selectCommissionTrend(distributorId, 7));
            overview.put("withdrawTrend", withdrawMapper.selectWithdrawTrend(distributorId, 7));

            return overview;
        } catch (Exception e) {
            log.error("获取分销商概览失败，distributorId: {}", distributorId, e);
            return new HashMap<>();
        }
    }

    // 私有方法：获取佣金比例
    private BigDecimal getCommissionRate(Integer level, Integer commissionType) {
        try {
            String configKey = "commission_rate_" + commissionType + "_" + level;
            String configValue = getDistributorConfig(configKey);
            
            if (StrUtil.isBlank(configValue)) {
                // 默认佣金比例
                return switch (level) {
                    case 1 -> new BigDecimal("5.0");
                    case 2 -> new BigDecimal("3.0");
                    case 3 -> new BigDecimal("2.0");
                    default -> BigDecimal.ZERO;
                };
            }
            
            return new BigDecimal(configValue);
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }

    // 私有方法：获取佣金类型名称
    private String getCommissionTypeName(Integer commissionType) {
        if (commissionType == null) return "未知";
        return switch (commissionType) {
            case 1 -> "注册佣金";
            case 2 -> "充值佣金";
            case 3 -> "VIP购买佣金";
            case 4 -> "服务订单佣金";
            case 5 -> "搭子佣金";
            default -> "未知";
        };
    }

    // 私有方法：获取佣金等级名称
    private String getCommissionLevelName(Integer commissionLevel) {
        if (commissionLevel == null) return "未知";
        return switch (commissionLevel) {
            case 1 -> "一级佣金";
            case 2 -> "二级佣金";
            case 3 -> "三级佣金";
            default -> "未知";
        };
    }

    // 私有方法：获取佣金状态名称
    private String getCommissionStatusName(Integer commissionStatus) {
        if (commissionStatus == null) return "未知";
        return switch (commissionStatus) {
            case 0 -> "待结算";
            case 1 -> "已结算";
            case 2 -> "已冻结";
            case 3 -> "已取消";
            default -> "未知";
        };
    }

    // 私有方法：获取提现状态名称
    private String getWithdrawStatusName(Integer withdrawStatus) {
        if (withdrawStatus == null) return "未知";
        return switch (withdrawStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核拒绝";
            case 3 -> "处理中";
            case 4 -> "已完成";
            case 5 -> "已失败";
            default -> "未知";
        };
    }

    // 私有方法：获取审核状态名称
    private String getAuditStatusName(Integer auditStatus) {
        if (auditStatus == null) return "未知";
        return switch (auditStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核拒绝";
            default -> "未知";
        };
    }

    // 私有方法：获取分销商状态名称
    private String getDistributorStatusName(Integer distributorStatus) {
        if (distributorStatus == null) return "未知";
        return switch (distributorStatus) {
            case 0 -> "禁用";
            case 1 -> "正常";
            case 2 -> "冻结";
            default -> "未知";
        };
    }

    // 私有方法：获取账户类型名称
    private String getAccountTypeName(Integer accountType) {
        if (accountType == null) return "未知";
        return switch (accountType) {
            case 1 -> "支付宝";
            case 2 -> "微信";
            case 3 -> "银行卡";
            case 4 -> "余额";
            default -> "未知";
        };
    }
} 